package com.hntxk.cqzd.pacs.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.CharStreams;
import com.hntxk.core.framework.service.impl.BaseServiceImpl;
import com.hntxk.core.util.DateUtil;
import com.hntxk.core.util.LoggerUtil;
import com.hntxk.cqzd.basicinfo.log.loginterface.service.InterfacelManageService;
import com.hntxk.cqzd.common.util.ComparatorDatePacs;
import com.hntxk.cqzd.lis.model.*;
import com.hntxk.cqzd.pacs.model.PacsModel;
import com.hntxk.cqzd.pacs.service.PacsInterfaceService;
import com.hntxk.sp.dict.manager.DictManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Component("PacesInterfaceServiceImpl")
@Slf4j
public class PacsInterfaceServiceImpl extends BaseServiceImpl<PacsModel> implements PacsInterfaceService {

    public static String  MAPPER_NAMESPACE = "com.hntxk.cqzd.pacs.mapper.PacsInterfaceMapper.";
    @Autowired
    @Qualifier("LogInterfaceService")
    InterfacelManageService interfacelManageService;
    @Autowired
    public PacsInterfaceServiceImpl() {
        super(MAPPER_NAMESPACE);
    }
        /**
         * 请求Paces数据
         * @return
         */
        @Override
        public List<PacsModel> getPaces(String outpatientNo,Integer dict){
            Integer it =1;
            if (dict!=null){
                it = dict;
            }
            List<PacsModel> pacsModels =new ArrayList<>();
            List<Object> objects = getDasTemplate().selectList(MAPPER_NAMESPACE+"selectHis",outpatientNo);
            if (ObjectUtils.isEmpty(objects)){
                return pacsModels;
            }
            HttpClient httpclient;
            HttpGet httpGet;
            HttpResponse response;
            for (Object o:objects) {
                String paces = o.toString();
//                详细json接口
//                String uri = "http://127.0.0.1:8008/commom/file/ceshiPac";
//                String uri = DictManager.getInstance().getDict("CQ_PACS_IFACE",it).getText()+outpatientNo;
                String uri = DictManager.getInstance().getDict("CQ_PACS_IFACE",it).getText()+paces;
//            String uri="http://192.168.10.175:7801/ExamReportPoint/fhir/DiagnosticReport?documentTypeCode=C0006-3&visitSqNo="+ outpatientNo;
                try {
                    httpclient = new DefaultHttpClient();
                    httpGet = new HttpGet(uri);
                    // 添加http头信息
//            Date businessTime = new Date(); // 业务时间，查询接口可不填
                    Date operationTime = new Date(); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
                    httpGet.addHeader("Content-Type", "application/fhir+json");
                    httpGet.addHeader("rootId", "2a15ce2b-f4f9-4599-9b2b-2c29b8378374"); // 调用方存储日志的id，用于追溯日志
                    httpGet.addHeader("token", "acae2b21-34b8-47eb-adec-6a2fbd51dc52"); // 调用接口中的业务号，例如使用患者流水号查询检验报告接口，此处填写患者就诊流水号
                    httpGet.addHeader("businessTime", ""); // 此接口对应的业务时间，如果是查询接口可不填
                    httpGet.addHeader("domain", "CHANQIANZD"); // 调用此接口的系统域，例如LIS、HIS、SPD
                    httpGet.addHeader("key", "ad0ce7db-40d9-4d85-8839-62c3b438aba3"); // 调用此接口的授权码，与系统域对应，一般是总线维护的授权码
                    httpGet.addHeader("operationTime", DateUtil.getStrByFormat( operationTime,"yyyy-MM-dd HH:mm:ss")); // 调用此接口的系统时间，一般是调用平台接口时new当时时间

                    response = httpclient.execute(httpGet);

                    // 检验状态码，如果成功接收数据
                    InputStream out = response.getEntity().getContent();
                    String result = CharStreams.toString(new InputStreamReader(out, Charsets.UTF_8));
//                System.out.println(result);
                    //解析数据
                    JSONObject jsonObject = JSON.parseObject(result);
                    JSONArray entry = (JSONArray) jsonObject.get("entry");
                    if(entry!=null&&entry.size()>0) {
                        for (int i = 0; i < entry.size(); i++) {
                            PacsModel pacsModel =new PacsModel();
                            JSONObject object = (JSONObject) entry.get(i);
                            if(object!=null) {
                                JSONObject entryJson = (JSONObject) object.get("resource");
                                if (entryJson != null) {
                                    Resource resource = JSON.parseObject(entryJson.toJSONString(), Resource.class);
//                            获取报告时间
                                    if (resource.getEffectiveDateTime()!=null){
                                        pacsModel.setEffectiveDateTime(resource.getEffectiveDateTime());
                                    }
                                    pacsModel.setResult(resource.getConclusion());

//                                解析resource
//                                解析identifier
                                    List<Identifier> identifiers = resource.getIdentifier();
                                    if (identifiers != null && identifiers.size() > 0) {
                                        String value = identifiers.get(0).getValue();
                                        pacsModel.setReportNo(value);
                                    }
//                                解析Extension
                            /*List<Extension> extensions = resource.getExtension();
                            if (extensions != null && extensions.size() > 0) {
                                for (Extension e : extensions) {
                                    if (e.getUrl().contains("1")) {

                                    }
                                }
                            }*/
//                                解析BasedOn
                                    List<BasedOn> basedOns = resource.getBasedOn();
                                    if (basedOns != null && basedOns.size() > 0) {
                                        for (BasedOn on : basedOns) {
                                            List<Extension> exts = on.getExtension();
                                            if (exts != null && exts.size() > 0) {
                                                for (Extension e : exts) {
                                                    if (e.getUrl().contains("requestNo")) {
                                                        pacsModel.setRequestNo(e.getValueString());
                                                    }
                                                    if (e.getUrl().contains("requestType")) {
                                                        pacsModel.setRequestTypeId(e.getValueCoding().getCode());
                                                        pacsModel.setRequestType(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("requestDoctor")) {
                                                        pacsModel.setRequestDoctorId(e.getValueCoding().getCode());
                                                        pacsModel.setRequestDoctor(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("requestDept")) {
                                                        pacsModel.setRequestDeptId(e.getValueCoding().getCode());
                                                        pacsModel.setRequestDept(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("examPosi")) {
                                                        pacsModel.setExamPosiId(e.getValueCoding().getCode());
                                                        pacsModel.setExamPosi(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("examMethod")) {
                                                        pacsModel.setExamMethodId(e.getValueCoding().getCode());
                                                        pacsModel.setExamMethod(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("examCategory")) {
                                                        pacsModel.setExamCategory(e.getValueString());
                                                    }
                                                    if (e.getUrl().contains("specialFlag")) {
                                                        pacsModel.setSpecialFlag(e.getValueBoolean());
                                                    }
                                                }
                                            }

                                        }
                                    }
//                                解析code
                                    Code code = resource.getCode();
                                    if (ObjectUtils.isNotEmpty(code)) {
                                        if (null != code.getText() && !"".equals(code.getText())) {
                                            pacsModel.setDocumentText(code.getText());
                                        } else {
                                            pacsModel.setDocumentText(null);
                                        }
                                        List<Coding> codings = code.getCoding();
                                        if (codings != null && codings.size() > 0) {
                                            pacsModel.setDocumentTypeId(codings.get(0).getCode());
                                            pacsModel.setDocumentType(codings.get(0).getDisplay());
                                        }
                                    }
//                                  解析subject
                                    Subject subject = resource.getSubject();
                                    if (subject != null) {
                                        List<Extension> subExtension = subject.getExtension();
                                        if (subExtension != null && subExtension.size() > 0) {
                                            for (Extension e : subExtension) {
                                                if (e.getUrl().contains("patientName")) {
                                                    pacsModel.setPatientName(e.getValueString());
                                                }
                                                if (e.getUrl().contains("gender")) {
                                                    pacsModel.setGenderId(e.getValueCoding().getCode());
                                                    pacsModel.setGender(e.getValueCoding().getDisplay());
                                                }
                                                if (e.getUrl().contains("age")) {
                                                    pacsModel.setAge(e.getValueString());
                                                }
                                                if (e.getUrl().contains("birthDate")) {
                                                    pacsModel.setBirthDate(e.getValueDate());
                                                }
                                                if (e.getUrl().contains("bedNo")) {
                                                    pacsModel.setBedNo(e.getValueString());
                                                }
                                                if (e.getUrl().contains("complaint")) {
                                                    pacsModel.setComplaint(e.getValueString());
                                                }
                                                if (e.getUrl().contains("symptomStartDate")) {
                                                    pacsModel.setSymptomStartDate(e.getValueDate());
                                                }
                                                if (e.getUrl().contains("symptomStopDate")) {
                                                    pacsModel.setSymptomStopDate(e.getValueDate());
                                                }
                                                if (e.getUrl().contains("symptomDescription")) {
                                                    pacsModel.setSymptomDescription(e.getValueString());
                                                }
                                            }
                                        }
                                    }
//                                解析contex
                                    Context context = resource.getContext();
                                    if (context != null) {
                                        List<Extension> conExtension = context.getExtension();
                                        for (Extension e : conExtension) {
                                            if (e.getUrl().contains("visitNo")) {
                                                pacsModel.setVisitNo(e.getValueString());
                                            }
                                            if (e.getUrl().contains("visitType")) {
                                                pacsModel.setVisitTypeId(e.getValueCoding().getCode());
                                                pacsModel.setVisitType(e.getValueCoding().getDisplay());
                                            }
                                            if (e.getUrl().contains("ward")) {
                                                pacsModel.setWardId(e.getValueCoding().getCode());
                                                pacsModel.setWard(e.getValueCoding().getDisplay());
                                            }
                                        }

                                    }
//                                解析performer
                                    List<Performer> performers = resource.getPerformer();
                                    if (performers != null && performers.size() > 0) {
                                        if (performers.get(0).getActor() != null) {
                                            Actor actor = performers.get(0).getActor();
                                            List<Extension> actExtenion = actor.getExtension();
                                            if (actExtenion != null && actExtenion.size() > 0) {
                                                for (Extension e : actExtenion) {
                                                    if (e.getUrl().contains("examDoctor")) {
                                                        pacsModel.setExamDoctorId(e.getValueCoding().getCode());
                                                        pacsModel.setExamDoctor(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("examDept")) {
                                                        pacsModel.setExamDeptId(e.getValueCoding().getCode());
                                                        pacsModel.setExamDept(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("examDate")){
                                                        pacsModel.setExamDate(e.getValueDate());
                                                    }
                                                    if (e.getUrl().contains("reportWriterDoctor")){
                                                        pacsModel.setReportWriterDoctorId(e.getValueCoding().getCode());
                                                        pacsModel.setReportWriterDoctor(e.getValueCoding().getDisplay());
                                                    }
                                                    if (e.getUrl().contains("reportWriterDept")){
                                                        pacsModel.setReportWriterDeptId(e.getValueCoding().getCode());
                                                        pacsModel.setReportWriterDept(e.getValueCoding().getDisplay());
                                                    }

                                                }
                                            }
                                        }
                                    }
//                                解析presentedForm
                                    List<PresentedForm> presentedForms = resource.getPresentedForm();
                                    if (presentedForms!=null&&presentedForms.size()>0){
                                        for (PresentedForm p :presentedForms){
                                            if (p.getUrl()!=null&& !"".equals(p.getUrl())){
                                                pacsModel.setUrl(p.getUrl());
                                            }
                                        }
                                    }
                                }
                            }
                            pacsModel.setOutPatientNo((String) o);
//                            pacsModel.setOutPatientNo("19");
                            pacsModel.setCardId(outpatientNo);
                            pacsModels.add(pacsModel);
                            log.info(pacsModel.getUrl()+":::"+pacsModel.getResult());
                        }
                    }
//                int code = response.getStatusLine().getStatusCode();
                } catch (Exception e) {
                  log.error("pcas接口错误,"+e.getMessage());
//                e.printStackTrace();
                }
            }
//            排序
            ComparatorDatePacs c = new ComparatorDatePacs();
            Collections.sort(pacsModels,c);
            return pacsModels;
        }
    }

